var Md5 = require('../utils/md5.js');
const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
};
const formatdate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  return [year, month].map(formatNumber).join('-')
};
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
};

function http(url, data, callback) {
  // data.key = getApp().globalData !== undefined ? getApp().globalData.key : '';
  data.key = wx.getStorageSync('key') !== undefined ? wx.getStorageSync('key') : '';
  data.timestamp = Date.parse(new Date()) / 1000;
  var sign = Md5.hexMD5(data.timestamp + 'iqidian' + data.key); //md5加密
  data.sign = sign;
  if (data.goods_list !== undefined) {
    data.goods_list = JSON.stringify(data.goods_list);
  }
  wx.request({
    url: getApp().globalData.http + url,
    data: data,
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    dataType: "json",
    success: function(res) {
      callback(res.data)
    },
    fail: function(res) {},
    complete: function(res) {},
  })
};

function message(msg) {
  wx.showModal({
    title: '温馨提示',
    content: msg,
    showCancel: false,
    success(res) {}
  })
}

function showLoading(msg) {
  wx.showLoading({
    mask: true,
    title: msg ? msg : '加载中',
  })
}

function hideLoading() {
  wx.hideLoading();
}

function in_array(search, array) {
  for (var i in array) {
    if (array[i]['id'] == search) {
      return true;
    }
  }
  return false;
}
//数据去重
function uniqueSearchRecord(newRecord) {
  var that = this;
  var listInfo = [];
  //加入缓存
  listInfo.push(newRecord);
  var listPost = wx.getStorageSync("listPost") || [];
  for (var i = 0; i < listPost.length; i++) {
    //如果当前数组的第i个已经保存进了临时数组，那么跳过，否者吧当前项push到临时数组里面
    if (!in_array(listPost[i]['id'], listInfo) && listPost[i].id !== newRecord && newRecord !== '' && newRecord !== null && newRecord !== undefined) {
      listInfo.push(listPost[i]);
    } else {
      listInfo[0].number = parseInt(listPost[i].number) + 1;
    }
  }
  wx.setStorageSync("listPost", listInfo);
}
//数据去重
function uniqueSearchRecord1(newRecord) {
  var that = this;
  var listInfo = [];
  //加入缓存
  listInfo.push(newRecord);
  var listPost = wx.getStorageSync("wholesaleCar") || [];
  for (var i = 0; i < listPost.length; i++) {
    //如果当前数组的第i个已经保存进了临时数组，那么跳过，否者吧当前项push到临时数组里面
    if (!in_array(listPost[i]['id'], listInfo) && listPost[i].id !== newRecord && newRecord !== '' && newRecord !== null && newRecord !== undefined) {
      listInfo.push(listPost[i]);
    } else {
      listInfo[0].number = parseInt(listPost[i].number) + 1;
    }
  }
  wx.setStorageSync("wholesaleCar", listInfo);
}

function countdown(that) {
  var EndTime = that.data.end_time || [];
  var NowTime = new Date().getTime();
  var total_micro_second = EndTime - NowTime || [];
  console.log('剩余时间：' + total_micro_second);
  // 渲染倒计时时钟
  that.setData({
    clock: dateformat(total_micro_second)
  });
  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止"
    });
    //return;
  }
  setTimeout(function() {
    total_micro_second -= 1000;
    countdown(that);
  }, 1000)
}

// 时间格式化输出，如11:03 25:19 每1s都会调用一次
function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second / 3600 / 24);
  // 小时
  var hr = Math.floor(second / 3600 % 24);
  // 分钟
  var min = Math.floor(second / 60 % 60);
  // 秒
  var sec = Math.floor(second % 60);
  return day + "天" + hr + "小时" + min + "分钟" + sec + "秒";
}
// getPastTime:判断发布过去时间间隔
function getPastTime(time) {
  // time为传入的时间戳        
  let date = new Date();
  let time1 = date.getTime();
  let time2 = (time1 - time) / 1000;
  let pastTimes = '';
  if (time2 < 300) {
    pastTimes = '刚刚';
  } else if (time2 >= 300 && time2 < 1800) {
    pastTimes = '5分钟前';
  } else if (time2 >= 1800 && time2 < 3600) {
    pastTimes = '30分钟前';
  } else if (time2 >= 3600 && time2 < 86400) {
    pastTimes = '1小时前';
  } else if (time2 >= 86400 && time2 < 259200) {
    pastTimes = '一天前';
  } else if (time2 >= 259200) {
    let date3 = new Date(time);
    pastTimes = date3.getFullYear() + '-' + (date3.getMonth() + 1) + '-' + date3.getDate();
  }
  return pastTimes;
}
let getQueryString = function(url, name) {
  console.log("url = " + url)
  console.log("name = " + name)
  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
  var r = url.substr(1).match(reg)
  if (r != null) {
    console.log("r = " + r)
    console.log("r[2] = " + r[2])
    return r[2]
  }
  return null;
}

function getJson(url) {
  var arr = url.split('?')[1].split('&')
  var theRequest = new Object();
  for (var i = 0; i < arr.length; i++) {
    var kye = arr[i].split("=")[0]
    var value = arr[i].split("=")[1]
    // 给对象赋值
    theRequest[kye] = value
  }
  return theRequest;
}

function setTabBarBadge() {
  var cartInfo = wx.getStorageSync("cartInfo") ? wx.getStorageSync("cartInfo") : [];
  var number = 0;
  cartInfo.forEach((value, index) => {
    number = number + value.number;
  })
  if (number == 0) {
    wx.removeTabBarBadge({
      index: 3,
    })
  } else {
    wx.setTabBarBadge({
      index: 3,
      text: String(number)
    })
  }
}
var time_range = function(strings) {
  var strings = strings.split("-")
  var beginTime = strings[0];
  var endTime = strings[1];
  var myDate = new Date();

  //获取当前年
  var year = myDate.getFullYear();

  //获取当前月
  var month = myDate.getMonth() + 1;

  //获取当前日
  var date = myDate.getDate();
  var h = myDate.getHours(); //获取当前小时数(0-23)
  var m = myDate.getMinutes(); //获取当前分钟数(0-59)
  var s = myDate.getSeconds();
  var nowTime = '' + h + ':' + m
  console.log('beginTime，endTime，nowTime', beginTime, endTime, nowTime)
  var strb = beginTime.split(":");
  if (strb.length != 2) {
    return false;

  }

  var stre = endTime.split(":");
  if (stre.length != 2) {
    return false;

  }

  var strn = nowTime.split(":");
  if (stre.length != 2) {
    return false;

  }
  var b = new Date();
  var e = new Date();
  var n = new Date();

  b.setHours(strb[0]);
  b.setMinutes(strb[1]);
  e.setHours(stre[0]);
  e.setMinutes(stre[1]);
  n.setHours(strn[0]);
  n.setMinutes(strn[1]);

  if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
    console.log("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，");
    return true;

  } else {
    console.log("当前时间是：" + n.getHours() + ":" + n.getMinutes() + "，不在该时间范围内！");
    return false;

  }

}

function share(path = null,title) {
  if (!path) {
    var pages = getCurrentPages() //获取加载的页面
    var currentPage = pages[pages.length - 1] //获取当前页面的对象
    var url = currentPage.route //当前页面url
    var options = currentPage.options //如果要获取url中所带的参数可以查看options
    var param = '';
    for (var key in options) {
      param += '&' + key + '=' + options[key]
    }
    var path = '/' + url + "?scene=0" + param;
  }
  path = escape(path);
  var redirect = '/pages/index/index?redirect=' + path;
  // unecape
  console.log('redirect', redirect)
	var lengthName = ""
	// console.log(title.length)
	if (title.length > 11) {
		lengthName = title.substring(0, 11)+"..."
	} else {
		lengthName = title
	}
  return {
    path: redirect,
	  title: lengthName,

  }
}

module.exports = {
  formatTime: formatTime,
  formatdate: formatdate,
  showLoading: showLoading,
  hideLoading: hideLoading,
  message: message,
  http: http,
  uniqueSearchRecord: uniqueSearchRecord,
  uniqueSearchRecord1: uniqueSearchRecord1,
  getPastTime: getPastTime,
  getQueryString: getQueryString,
  getJson: getJson,
  setTabBarBadge: setTabBarBadge,
  time_range: time_range,
  share: share
}